package com.restaurant.springboot.service.impl;

import com.restaurant.springboot.entity.UserEntity;
import com.restaurant.springboot.entity.WechatInfoEntity;
import com.restaurant.springboot.entity.WechatOpenIdResp;
import com.restaurant.springboot.repositories.UserRepository;
import com.restaurant.springboot.utils.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;

@Service
public class UserServiceImpl implements com.restaurant.springboot.service.UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    WechatUtil wechatUtil;

    @Override
    public UserEntity getUser(String openId) {
        return userRepository.getUserEntityByOpenId(openId);
    }

    @Override
    public boolean userIsExit(String openId) {
        return userRepository.existsByOpenId(openId);
    }

    @Override
    @Transient
    public boolean updateUser(UserEntity user) {
        if (userRepository.save(user) != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public UserEntity getUserById(int id) {
        return userRepository.findById(id).get();
    }

    /**
     * 如果已经注册那么结束注册
     * @param code 临时凭证
     * @return 是否注册成功
     */
    @Override
    public boolean registerUser(String code,String nickName,String url) {
        WechatOpenIdResp wechatOpenIdResp = wechatUtil.getWechatOpenId(code);
        if (wechatOpenIdResp.getErrcode() == 0) {
            String openId = wechatOpenIdResp.getOpenid();
            UserEntity allByOpenId = userRepository.getUserEntityByOpenId(openId);
            if(allByOpenId !=null){
                return false;
            }
            UserEntity userEntity = new UserEntity();
            userEntity.setOpenId(openId);
            userEntity.setName(nickName);
            userEntity.setPhotoUrl(url);
            userRepository.save(userEntity);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public String getOpenId(String code) {
        WechatOpenIdResp wechatOpenIdResp = wechatUtil.getWechatOpenId(code);
        if (wechatOpenIdResp.getErrcode() == 0) {
            String openId = wechatOpenIdResp.getOpenid();
            return openId;
        }else{
            return null;
        }
    }
}
